﻿@inject NavigationManager NavigationManager
@inject IChatService _chatService
@inject IDialogService _dialogService
@inject ChatState _chatState

<MudListItem OnClick="@NavigateToChat" Value="@ChatSessionItem!.Id">
    <ChildContent>
        <div class="d-flex flex-row flex-grow-1">
            <MudAvatar Size="@Size.Medium" Class="my-auto mr-4">
                <MudImage Src="@(!string.IsNullOrEmpty(ChatSessionItem.AssignedAssistant?.AvatarUrl) ? ChatSessionItem.AssignedAssistant?.AvatarUrl : DefaultAvatarUrl)" />
            </MudAvatar>
            
            @if(shouldShowTooltip)
            {
                <div class="my-auto" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100%">
                    <MudTooltip Placement="Placement.Bottom" Arrow="true" Text="@ChatSessionItem?.Title" Style="max-width: 450px; overflow-wrap: break-word;">
                        <MudText Typo="Typo.body1" Class="my-auto" Style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex-grow: 1;">@(TruncateText(@ChatSessionItem!.Title, 38)) </MudText>
                    </MudTooltip>
                </div>
            }
            else
            {
                <MudText Typo="Typo.body1" Class="my-auto" Style="overflow: hidden; white-space: nowrap; flex-grow: 1;">@ChatSessionItem?.Title</MudText>
            }

            <MudSpacer />
            <MudMenu Icon="@Icons.Material.Filled.MoreVert">
                <MudMenuItem OnClick="OpenChangeTitleDialog">Rename</MudMenuItem>
                <MudMenuItem OnClick="ConfirmDeleteChatDialog">Delete</MudMenuItem>
            </MudMenu>
        </div>
    </ChildContent>
</MudListItem>
<MudDivider />

@code
{
    [Parameter] public ChatSessionResponse? ChatSessionItem { get; set; }
    [Parameter] public EventCallback<ChatSessionResponse> OnDeleteChat { get; set; }
    [Parameter] public EventCallback<ChangeTitleInfo> OnChangeTitle { get; set; }

    private const string DefaultAvatarUrl = "https://raw.githubusercontent.com/ktutak1337/Stellar-Chat/main/docs/assets/images/_1863a13f-cfb3-454d-ada0-34595b28c2e6.jpg";
    private bool shouldShowTooltip;

    protected override void OnParametersSet()
    {
        shouldShowTooltip = ChatSessionItem?.Title?.Length > 37;
    }

    private void NavigateToChat()
    {
        _chatState.SetChatId(ChatSessionItem!.Id);
        NavigationManager.NavigateTo($"/c/{ChatSessionItem.Id}");
    }

    private async Task ConfirmDeleteChatDialog()
    {
        var parameters = new DialogParameters
        {
            { "Message", $"This will delete the conversation: '{ChatSessionItem?.Title}'." },
            { "DetailMessage", "This action cannot be undone." }
        };

        var options = new DialogOptions { CloseOnEscapeKey = true };
        var dialog = _dialogService.Show<ConfirmDialog>("Delete this chat?", parameters, options);

        var result = await dialog.Result;

        if (!result.Canceled)
        {
            await OnDeleteChat.InvokeAsync(ChatSessionItem);
        }
    }

    private async Task OpenChangeTitleDialog()
    {
        var parameters = new DialogParameters();
        parameters.Add(nameof(ChatSessionItem), ChatSessionItem);

        var options = new DialogOptions { CloseOnEscapeKey = true };
        var dialog = _dialogService.Show<ChangeChatSessionTitleDialog>("Change title", parameters, options);

        var result = await dialog.Result;

        if (!result.Canceled)
        {
            var updatedTitle = result.Data as string;

            if (!string.IsNullOrEmpty(updatedTitle))
            {
                var changeTitleInfo = new ChangeTitleInfo(ChatSessionItem!.Id, updatedTitle);
                await OnChangeTitle.InvokeAsync(changeTitleInfo);
            }
        }
    }

    private string TruncateText(string text, int maxLength) 
        => text.Length > maxLength ? $"{text.Substring(0, maxLength - 3)}..." : text;
}
